//
//  MSAFNManage+extension.swift
//  SwiftWeibo
//
//  Created by 牟松 on 16/8/9.
//  Copyright © 2016年 DoNews. All rights reserved.
//

import Foundation

extension MSAFNManage{
    
    // 请求微博列表
    

    func statesListRequest(since_id: Int64 = 0, max_id: Int64 = 0,  completion: (statesList: [[String: AnyObject]]?, isSuccess: Bool) -> ()){
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        var params = [String: AnyObject]()
        
        params["since_id"] = "\(since_id)"
        params["max_id"] = max_id > 0 ? "\(max_id-1)" : "\(max_id)" // 防止有重复微博
        
        accresstokenRequest(urlString: urlString, params: params) { (json, isSuccess) in
            let statesList = json?["statuses"] as? [[String : AnyObject]]
            
            completion(statesList: statesList, isSuccess: isSuccess)
        }
                
    }
    
    // 获取用户的各种未读数
    func getUserUnreadCount(completion:(dict: [String: AnyObject])->()) {
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let params = ["uid": uid]
        accresstokenRequest(urlString: urlString, params: params) { (json, isSuccess) in
            
            completion(dict: (json as? [String: AnyObject]) ?? [:])
        }
    
    }
    // 获取用户信息
    func getUserInfoRequest(completion:(dict:[String: AnyObject])->()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        guard let uid = userAccount.uid else {
            return
        }
        let params = ["uid": uid]
        accresstokenRequest(urlString: urlString, params: params){ (json, isSuccess) in
            completion(dict: (json as? [String: AnyObject]) ?? [:])
            
        }
        
        
    }
    // 获取accresstoken的请求
    func getAccountInfoRequest(codeString: String, completion:(isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": APPKEY,
                      "client_secret": APPSECRET,
                      "grant_type": "authorization_code",
                      "code": codeString,
                      "redirect_uri": redirect]
        request(method: .POST, urlString: urlString, params: params) { (json, isSuccess) in
            print(json)
            
            
            self.userAccount.yy_modelSet(with:(json as? [String: AnyObject]) ?? [:])
            
            
            self.getUserInfoRequest(completion: { (dict) in
                self.userAccount.yy_modelSet(with: dict)
                
                print("============\(dict)")
                
                self.userAccount.saveUserAccountInfo()
                
                completion(isSuccess: isSuccess)
            })
    
        }
       
    }
    
}
